package com.nlscan.qdkit.ui.publico.util;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.signature.ObjectKey;
import com.nlscan.qdkit.ui.publico.R;
import com.quvii.qvlib.util.LogUtil;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统服务工具类
 * <p>
 * Created by QING on 2017/12/6.
 */

public class SystemUtil {


//    public static void vibrate(long milliseconds) {
//        vibrate(App.getInstance(), milliseconds);
//    }

    /**
     * 震动milliseconds毫秒
     */
//    public static void vibrate(final Context context, long milliseconds) {
//        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
//        if (vib.hasVibrator()) {
//            vib.vibrate(milliseconds);
//        }
//    }
//
//    //以pattern[]方式震动
//    public static void vibrate(final Context context, long[] pattern, int repeat) {
//        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
//        if (vib.hasVibrator()) {
//            vib.vibrate(pattern, repeat);
//        }
//    }
//
//    //取消震动
//    public static void virateCancle(final Context context) {
//        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
//        // TODO: 2017/12/6 多线程同时调用关闭会抛出异常
//        vib.cancel();
//    }

    /**
     * 获取当前应用程序的版本号。
     */
    public static int getAppVersionCode(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 使用MD5算法对传入的key进行加密并返回。
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 添加图片显示渐现动画
     */
//    public static void setImageBitmap(ImageView imageView, Bitmap bitmap,
//                                      boolean isTran) {
//        if (isTran) {
//            final TransitionDrawable td = new TransitionDrawable(
//                    new Drawable[]{
//                            new ColorDrawable(android.R.color.transparent),
//                            new BitmapDrawable(bitmap)});
//            td.setCrossFadeEnabled(true);
//            imageView.setImageDrawable(td);
//            td.startTransition(300);
//        } else {
//            imageView.setImageBitmap(bitmap);
//        }
//    }
    public static boolean isVideoFileUri(String uri) {
        String mimeType = getMimeType(uri);
        return mimeType != null && mimeType.startsWith("video/");
    }

    public static String getMimeType(String path) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(path);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                extension);
        if (mimeType == null) {
            return "*/*";
        }
        return mimeType;
    }

    /**
     * 获取视频缩略图 值得注意的是，此为耗时操作，需要在非ui线程中操作
     *
     * @param filePath
     * @return
     */
    public static Bitmap getVideoThumbnail(String filePath) {
        return ThumbnailUtils.createVideoThumbnail(filePath,
                MediaStore.Images.Thumbnails.MINI_KIND);
    }

    public static boolean isImageFileUri(String uri) {
        String mimeType = getMimeType(uri);
        return mimeType != null && mimeType.startsWith("image/");
    }

    /**
     * @param str
     * @return
     */
    public static String removeLineFeed(String str) {
        String dest = "";
        if (!TextUtils.isEmpty(str)) {
            Pattern p = Pattern.compile("\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 获取 AndroidId
     */
    public static String getAndroidId(Context con) {

        String androidId = android.provider.Settings.Secure.getString(
                con.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);
        LogUtil.i("ANDROID_ID", "androidId:" + androidId);
        return androidId;
    }


//    public static void setTextViewSwitchState(TextView textView, boolean enable) {
//        if (textView == null) {
//            return;
//        }
//
//        Drawable drawable = App.getInstance().getResources().getDrawable(
//                enable ? R.drawable.alarmmangement_btn_on : R.drawable.alarmmangement_btn_off
//        );
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//
//        if (RtlUtils.isRTL()) {
//            textView.setCompoundDrawables(drawable, null, null, null);
//        } else {
//            textView.setCompoundDrawables(null, null, drawable, null);
//        }
//    }

//    public static void setTextViewEndIcon(TextView textView, int iconRes) {
//        if (textView == null) {
//            return;
//        }
//
//        Drawable drawable = App.getInstance().getResources().getDrawable(iconRes);
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//
//        if (RtlUtils.isRTL()) {
//            textView.setCompoundDrawables(drawable, null, null, null);
//        } else {
//            textView.setCompoundDrawables(null, null, drawable, null);
//        }
//    }

    public static void SetImage(ImageView imageView, String path) {
        SetImage(imageView.getContext(), imageView, path, false);
    }

    public static void SetImage(ImageView imageView, int cover, String path) {
        SetImage(imageView.getContext(), imageView, path, cover, false);
    }

    public static void SetImage(Context context, ImageView image, String path) {
        SetImage(context, image, path, false);
    }

    public static void SetImage(Context context, ImageView image, String path, boolean isGaussianBlur) {
        SetImage(context, image, path, R.drawable.device_cover_default, isGaussianBlur);
    }

    public static void SetImage(Context context, ImageView image, String path, int cover, boolean isGaussianBlur) {
        RequestOptions options = new RequestOptions()
                .placeholder(cover)
                .error(cover)
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

        if (isGaussianBlur) {
            options.transform(new GaussianBlurTransformation());
        }

        File file = new File(path);
        if (!file.exists()) {
            LogUtil.i("file not exist: " + path);
            Glide.with(context).load(cover).apply(options).into(image);
            return;
        }

        options.signature(new ObjectKey(file.lastModified()));
        Glide.with(context).load(file).apply(options).into(image);
    }

    public static void showViewInfo(View view) {
        LogUtil.i(generateTag(getCallerStackTraceElement()), "View Info: "
                + " left = " + view.getLeft()
                + " right = " + view.getRight()
                + " top = " + view.getTop()
                + " bottom = " + view.getBottom()
                + " x = " + view.getX()
                + " y = " + view.getY()
                + " translation x = " + view.getTranslationX()
                + " translation y = " + view.getTranslationY()
                + " width = " + view.getWidth()
                + " height = " + view.getHeight()
        );
    }

    private static String generateTag(StackTraceElement caller) {
        String tag = "%s.%s(L:%d)";
        String callerClazzName = caller.getClassName();
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
        tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber());
        return tag;
    }

    public static StackTraceElement getCallerStackTraceElement() {
        return Thread.currentThread().getStackTrace()[4];
    }

//    public static void restartApp(Activity activity) {
//        restartApp(activity, StartActivity.class);
//    }

    public static void restartApp(Activity activity, Class<?> homeClass) {

        SpUtil.getInstance().setIsLogin(false);
        SpUtil.getInstance().setLocalLogin(false);
        NotificationManager nm = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(1);

        Intent intent = new Intent(activity, homeClass);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);

        // 杀掉进程，不加这句，会导致Unable to destroy activity 报错
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static void setForceDarkNotAllowed(View... views) {
        if (views == null) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            for (View view : views) {
                if (view != null) {
                    view.setForceDarkAllowed(false);
                }
            }
        }
    }
}
